import {request} from '../../../../utils/request';
import api from '../../../../utils/api';
Page({
    data:{
        param:{},
        page:1,
        list:[],
        recommend:[],
        title:{},
        active:0,
        days:[],
        show: false,
        select: {}
    },
    onClickLeft(){
        wx.navigateBack({delta: 1})
    },
    onLoad(event){
        let property = wx.getStorageSync('property')[event.type];
        this.setData({param: event, title: property});
        this.getTrain(false);
        this.getDatesAndWeekdaysForNextFiveDays();
    },
    getTrain(flag){
        let property = wx.getStorageSync('property');
        wx.showLoading({
          title: '正在全力搜索..',
        })
        let path = this.data.param.type == 2 ? api.TICKET_TRAIN_LIST : api.TICKET_AIRPORT_LIST;
        request(path, {
            fromCode: property[this.data.param.type].positionCode,
            toCode:  property[this.data.param.type].destinationCode,
            page: this.data.page,
            toTime: this.data.param.startTime,
            size: 10
        }, "POST").then(result => {
            if(result.code == 200) {
                result.body.forEach(item =>{
                    item.personNumber = 1;
                    item.spaceMoney = item.totalPrice == null ? item.atp : item.totalPrice;
                    if(this.data.param.type == 2) item.number = item.number.split(",");
                    else item.sts = JSON.parse(item.sts).slice(0, 3); 
                })
                if(flag){
                    this.data.list.push(...result.body);
                    this.setData({list: this.data.list});
                }else
                    this.setData({list: result.body});
            }
            wx.hideLoading()
        })
    },
    getDatesAndWeekdaysForNextFiveDays() {
        const today = new Date(); // 获取当前日期
        const datesAndWeekdays = [];
      
        for (let i = 0; i < 5; i++) { // 循环5次，对应未来5天
          const nextDay = new Date(today.getTime()); // 创建一个新的日期对象，基于当前日期
          nextDay.setDate(today.getDate() + i + 1); // 设置日期为当前日期加i天（+1是因为我们想要明天开始）
      
          // 格式化日期输出，例如："YYYY-MM-DD"
          const formattedDate =(nextDay.getMonth() + 1).toString().padStart(2, '0') + '-' +
                                nextDay.getDate().toString().padStart(2, '0');
      
          // 获取对应的星期几（0 - Sunday, 1 - Monday, ..., 6 - Saturday）
          const weekdayIndex = nextDay.getDay();
      
          // 根据weekdayIndex获取对应的星期名称
          const weekdays = ['周末', '周一', '周二', '周三', '周四', '周五', '周六'];
          const weekdayName = weekdays[weekdayIndex];
      
          datesAndWeekdays.push({
            date: formattedDate,
            weekday: weekdayName
          });
        }
        this.setData({days: datesAndWeekdays});
      },
      onChange(event){
        this.setData({page: 1});
        this.setData({'param.startTime': event.detail.title});
        this.getTrain(false);
      },
      show(obj){
          this.setData({show: true, select: obj.currentTarget.dataset.obj});
      },
      onClose(){
        this.setData({show: false});
      },
      selectNumber(event){
         this.setData({
            "select.selectNumber": event.currentTarget.dataset.number
         })
      },
      onReachBottom(){
          this.setData({page: this.data.page + 1});
          this.getTrain(true);
      },
      setPsersonNumber(event){
          if(this.data.param.type == 1){
              this.setData({"select.spaceMoney": this.data.select.atp * event.detail});
              return;
          }
        this.setData({ 
            "select.spaceMoney": this.data.select.totalPrice * event.detail,
            "select.personNumber": event.detail
        })
      },
      createOrder(){
          let obj = this.data.select;
          if(this.data.param.type == 2 && obj.selectNumber == null){
              wx.showToast({
                title: '请选择乘坐的班次',
                icon: 'error'
              })
              return;
          }
          request(api.TICKET_CREATE_ORDER, {
                type: this.data.param.type == 2 ? 1 : 2,
                productId: obj.id,
                personNumber: obj.personNumber,
                toTime: this.data.days[this.data.active].date + " " + (obj.fromTime == null ? obj.dst : obj.fromTime),
                price: obj.spaceMoney,
                no: obj.selectNumber == null ? obj.fn : obj.selectNumber
          }, "POST").then(result => {
              if(result.code == 200){
                  this.setData({show: false});
                  wx.showToast({
                    title: result.body,
                    icon: "success"
                  })
              }else wx.showToast({
                title: result.body,
                icon: 'error'
              })
          })
      }
      
})